# -*- coding: utf-8 -*-
'''
#----------------------------------------------------------------------------------------
# 功能：seven基础工作库
#----------------------------------------------------------------------------------------
'''


import json
from flib.utils import *


class ZLException(Exception):
    def __init__(self, str):
        self.str = str

    def __str__(self):
        return self.str


# 获取客户端link版本号
def GetLinkVersion(filepath):
    f = open(filepath, "r")
    content = f.read()
    f.close()

    pos = content.find(r'''def.static("=>", "number").GetLinkVersion = function ()''')
    pos2 = content.find("return", pos)
    pos3 = content.find("end", pos2)
    bpos = pos2 + 7
    version = content[bpos:pos3 - 1]
    return int(version)


# 获取资源版本号
def GetResBaseVersion(filepath):
    from xml.dom.minidom import parse
    import xml.dom.minidom
    file_xml = open(filepath, "r").read()
    file_xml = file_xml.replace('<?xml version="1.0" encoding="gb2312"?>', '<?xml version="1.0" encoding="utf-8"?>')
    file_xml = file_xml.replace('<?xml version="1.0" encoding="gbk"?>', '<?xml version="1.0" encoding="utf-8"?>')
    try:
        file_xml = toUTF8(file_xml)
    except Exception as e:
        pass
    domtree = xml.dom.minidom.parseString(file_xml)
    root = domtree.documentElement
    ele = root.getAttribute("value")
    return ele


# 获取当前version, 主要用在ios判断审核模式
def GetLocalVersionValue(filepath):
    from xml.dom.minidom import parse
    import xml.dom.minidom
    file_xml = open(filepath, "r").read()
    file_xml = file_xml.replace('<?xml version="1.0" encoding="gb2312"?>', '<?xml version="1.0" encoding="utf-8"?>')
    file_xml = file_xml.replace('<?xml version="1.0" encoding="gbk"?>', '<?xml version="1.0" encoding="utf-8"?>')
    try:
        file_xml = toUTF8(file_xml)
    except Exception as e:
        pass
    domtree = xml.dom.minidom.parseString(file_xml)
    root = domtree.documentElement
    ele = root.getAttribute("value")
    return int(ele)


# 获取客户端工程子目录地址
def GetClientSubPth(branch, platform):
    dir_name, extname = "PC", "Win"
    if platform == "android":
        dir_name = "Android"
        extname = "Android"
    elif platform == "ios":
        dir_name = "IOS"
        extname = "IOS"
    elif platform != "win" and platform != "pc":
        raise ZLException("platform {0} is not support.".format(platform))
    return branch + "/" + dir_name + "/ElementUnity" + extname


# 写入环境变量文件
def WriteEnvFile(filepath, key, value):
    f = open(filepath, "a")
    f.write("{key}={value}\n".format(key=key, value=value))
    f.close()


# 修改entrypoing.confi配置參數
def UpdateEntryPointConfig(filepath, autoupdate=True, createconsole=False, luachecklevel=0):
    if not filepath:
        exit(-1)
        return False
    if not os.path.exists(filepath):
        return True
    safe_execute('''svn revert "{}"'''.format(filepath))
    with open(filepath, "r") as f:
        try:
            jConfig = json.load(f)
            ZLPrint("AUTO_UPDATE:", autoupdate)
            # 是否需要更新
            if autoupdate:
                jConfig["noresourceupdate"] = False
                jConfig["noprogramupdate"] = False
            else:
                jConfig["noresourceupdate"] = True
                jConfig["noprogramupdate"] = True
            # 是否默认打开控制台
            jConfig[
                "createconsole"] = createconsole  # False if getenv("UPDATE_PLATFORM") == "ios" else getenv("CREATE_CONSOLE") == "true" #正式版默认关闭控制台
            # lua检查等级
            jConfig["luachecklevel"] = luachecklevel  # 0 if getenv("UPDATE_PLATFORM") == "ios" else 2 #正式版需要关闭lua检查

            f.close()
            with open(filepath, "w") as f:
                json.dump(jConfig, f)
            for k in jConfig:
                ZLPrint("               ", k, ":", jConfig[k])
        except Exception, e:
            ZLPrint("[error]", e)
            return False
    return True


def UpdateEntryPointConfigEx(filepath, **kw):
    with open(filepath, "r") as f:
        jConfig = json.load(f)
        for k in kw:
            ZLPrint(k, "=", kw[k])
            jConfig[k] = kw[k]
        f.close()
        with open(filepath, "w") as fout:
            json.dump(jConfig, fout)
            fout.close()
        ZLPrint(jConfig)


# 获取最新资源版本号
def GetRescourceVersion(url):
    if not url:
        raise ZLException("url is empty")
    strcmds = '''
    curl_op()
    {
        curl -i -s -S ${1+"$@"} | iconv -f gbk -t utf-8
        if [ ! $? ]; then
            echo>&2 "[error] curl 操作失败: curl $@"
            quit 1
        fi
    }

    content=$(curl_op -L "$1")

    content=${content#*Database Created On}
    content=${content#*Version }
    content=${content%%(*}
    echo "$content"
    '''
    result = exec_sh(cmds=strcmds, logout=False, args=[url])
    if result and len(result) == 1:
        return result[0]
    else:
        raise ZLException("can not get resource version from " + url if not result else result[0])


if __name__ == '__main__':
    v = GetLinkVersion('''F:/Seven/ElementUnityWin/Output/Lua/Configs/ClientCfg.lua''')
    v2 = GetLocalVersionValue(
        '''F:/Seven/ElementUnityWin/UnityProject/Assets/StreamingAssets/config/local_version.xml''')
    print(GetClientSubPth("ob", "android"))
    WriteEnvFile("F:/apk_propfile.txt", "test", "hell2o")
    WriteEnvFile("F:/apk_propfile.txt", "test", "hell2o")
    print v, v2
    print(
    GetResBaseVersion('''F:/Seven/ElementUnityWin/UnityProject/Assets/StreamingAssets/res_base/res_base_version.xml'''))
    UpdateEntryPointConfig('''F:/Seven/ElementUnityWin/UnityProject/Assets/StreamingAssets/entrypoint.config''',
                           autoupdate=True, luachecklevel=2)
    try:
        print GetRescourceVersion("http://10.236.100.108/seven_global/fabu/ios/cgi/index.cgi")
    except Exception as e:
        print e
    UpdateEntryPointConfigEx('''F:/Seven/ElementUnityWin/UnityProject/Assets/StreamingAssets/entrypoint.config''',
                             createconsole2=True, noresourceupdate=True)

